package rtm.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import rtm.core.BaseResponseHandler;
import rtm.core.CommandFacade;
import rtm.core.UrlBuilder;

public class TaskListHandler extends BaseResponseHandler {

	/*
	 * <taskseries id="9572443" created="2008-01-21T01:41:36Z"
	 * modified="2008-02-18T12:14:49Z" name="Call PF" source="gmail" url=""
	 * location_id="">
	 * 
	 * <tags> <tag>canada</tag> </tags> <participants/> <notes/> <task
	 * id="14163588" due="2008-01-21T02:00:00Z" has_due_time="0"
	 * added="2008-01-21T01:41:36Z" completed="2008-02-18T12:14:49Z" deleted=""
	 * priority="N" postponed="0" estimate=""/> </taskseries>
	 */

	private List<Task> tasks = new ArrayList<Task>();

	private Task current;

	private boolean receivingTag;

	@Override
	public void characters(char[] ch, int start, int length) {

		if (receivingTag) {
			current.addTag(new String(ch, start, length));
		}
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {

		super.startElement(uri, localName, name, attributes);

		if ("taskseries".equals(name)) {

			current = new Task();
			current.setName(attributes.getValue("name"));

		} else if ("task".equals(name)) {

			current.setId(Integer.parseInt(attributes.getValue("id")));

			final String due = attributes.getValue("due");
			if (!"".equals(due)) {
				current.setDue(new Date());
			}

			tasks.add(current);
			current = null;

		} else if ("tag".equals(name)) {

			receivingTag = true;
		}
	}

	public List<Task> getTasks() {
		return tasks;
	}
}
